package com.mingqijia.gassafety.console.controller.workorder;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gap.basic.base.CommonResponse;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.OperateRecordEnum;
import com.mingqijia.gassafety.shared.log.LogRecord;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.workorder.mbp.*;
import com.mingqijia.gassafety.webserver.response.HistoryAlarmAndBrokenResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.HistoryListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.asst.WorkingOrderListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.mbp.AppealHistoryResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.service.workorder.mbp.MbpWorkOrderService;
import com.mingqijia.gassafety.webserver.webSocket.WebSocketDpProcess;

import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.hutool.json.XMLTokener.entity;
import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_GAS;

/**
 * <p>
 * TCIS MBP接口
 *
 * @author guoliang.lao
 * @since 2022-11-16
 */

@Slf4j
@Api(tags = "TCIS MBP接口")
@RestController(value = "MbpController")
@RequestMapping("/business/v1/work/order/tcis/mbp")
public class MbpController {

    @Autowired
    MbpWorkOrderService mbpWorkOrderService;
    @Autowired
    HeaderUtil headerUtil;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;
    @Autowired
    WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisCacheExt redisUtil;

    @Resource
    WebSocketDpProcess webSocketDpProcess;

    @Autowired
    FieldTemplateService fieldTemplateService;


    @ApiOperation("查询历史工单")
    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public CommonResponse<PageUtil<HistoryListResponse>> historyList(@RequestParam @ApiParam(value = "设备号") @NotNull String imei,
                                                                     @RequestParam @NotNull Integer page,
                                                                     @RequestParam @NotNull Integer pageSize){
        return CommonResponse.success(mbpWorkOrderService.historyList(imei,page,pageSize));
    }

    @ApiOperation("进行中的工单")
    @RequestMapping(value = "/workingOrder", method = RequestMethod.GET)
    public CommonResponse<PageUtil<WorkingOrderListResponse>> workingOrderList(@RequestParam @ApiParam(value = "设备号")@NotNull String imei,
                                                                               @RequestParam @NotNull Integer page,
                                                                               @RequestParam @NotNull Integer pageSize){
        return CommonResponse.success(mbpWorkOrderService.workingOrderList(imei,page,pageSize));
    }

    @LogRecord(operateType = OperateRecordEnum.OPERATE_TYPE_40)
    @ApiOperation(value = "发起安装工单-客户管理-模板一")
    @PostMapping("/initiateWorkOrder")
    public CommonResponse<Object> initiateWorkOrder(@RequestBody @Valid InitiateWorkOrderRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());
//        if (BIND_CHANNEL_GAS !=request.getTemplateType()){
//            throw new BizException("只允许模板一调用本接口");
//        }
        mbpWorkOrderService.initiateWorkOrder(request);
        return CommonResponse.success("success");
    }

    @ApiOperation("MBP预约服务")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResponse<Object> create(@RequestBody MbpOrderCreateRequest req){
        log.info("MBP预约服务 req:{}",req.toString());
        //分布式锁，防止重复提交
        String key = Constants.ADD_EQUIPMENT + req.getImei();
        Boolean absent = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), 5L);
        if (absent){
            try {
                if (req.getStatus() != 1) {
                    //检查该设备是否存在正在进行的维修工单
                    LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper<>();
                    String imei = req.getImei();
                    if (req.getImei().contains("-")) {
                        imei = req.getImei().split("-")[0];
                    }
                    queryWrapper.eq(WorkOrderHistory::getDeviceId,imei).eq(WorkOrderHistory::getHandleStatus,0)
                            .eq(WorkOrderHistory::getIsDeleted,0);
                    List<WorkOrderHistory> list = workOrderHistoryService.list(queryWrapper);
                    if (!CollectionUtils.isEmpty(list)){
                        return CommonResponse.failure("该设备存在已进行中的维修工单", req.getImei());
                    }
                }
                if (req.getIsSmartKitchen()){
                    mbpWorkOrderService.appealKitchenRecord(req);
                }else {
                    mbpWorkOrderService.appealAlarmSystem(req);
                }

                sendDpMessage();

                return CommonResponse.success(null);
            }catch (Exception e){
                log.error("MBP预约服务异常：", e);
                return CommonResponse.failure(e.getMessage());
            }finally {
                redisUtil.del(key);
            }
        }else {
            return CommonResponse.success("重复提交，不处理");
        }
    }


    @ApiOperation("MBP批量处理")
    @RequestMapping(value = "/batchAppeal", method = RequestMethod.POST)
    public CommonResponse<Object> batchAppeal(@RequestBody MbpOrderCreateRequest req){
        log.info("MBP批量处理 req:{}",req.toString());
        String spId = ApplicationUtils.getWorkingSpId();
        //已处理
        if (req.getStatus() == 1) {
            for (String id : req.getIds()) {
                AppealLog appealLog = new AppealLog();
                appealLog.setAlarmBrokenId(Long.parseLong(id));
                appealLog.setAppealStatus(Constants.APPEAL_STATUS_2);
                appealLog.setAppealResult(req.getAppealResult());
                appealLog.setSpId(spId);
                appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                if (req.getBizType().equals(2)) {
                    appealLog.setAppealType(0);
                } else if (req.getBizType().equals(3)) {
                    appealLog.setAppealType(1);
                }
                log.info("新增报警诉求记录："+appealLog.toString());
                appealLogService.save(appealLog);
                // 更新报警/故障信息记录主表
                if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarm = new HistoryAlarm();
                    historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                    historyAlarm.setAppealResult(appealLog.getAppealResult());
                    historyAlarm.setUserName(appealLog.getUserName());
                    historyAlarm.setUserAccount(appealLog.getUserAccount());
                    historyAlarm.setAppealTime(appealLog.getCreatedAt());
                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                } else if (appealLog.getAppealType() == 1) {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBroken = new HistoryBroken();
                    historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyBroken.setAppealStatus(appealLog.getAppealStatus());
                    historyBroken.setAppealResult(appealLog.getAppealResult());
                    historyBroken.setUserName(appealLog.getUserName());
                    historyBroken.setUserAccount(appealLog.getUserAccount());
                    historyBroken.setAppealTime(appealLog.getCreatedAt());
                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                }
            }
        } else if (req.getStatus() == 2) {
            //转工单
            Long workOrderId;
            MbpOrderCreateRequest params = new MbpOrderCreateRequest();
            BeanUtils.copyProperties(req,params);
            QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                    .eq(FieldTemplate::getTemplateType, 1)
                    .eq(FieldTemplate::getIsDeleted, 0);
            FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
            if (req.getBizType() == 2) {
                if (fieldTemplate.getAlarmHandleType() == 3) {
                    workOrderId = mbpWorkOrderService.createQuotitentOrder(req);
                } else if (fieldTemplate.getAlarmHandleType() == 2) {
                    workOrderId = mbpWorkOrderService.createNewOrder(req);
                } else {
                    if (isInnerBuy(req.getImei(), spId)) {
                        MbpInnerCreateRequest innerCreateRequest = new MbpInnerCreateRequest();
                        BeanUtils.copyProperties(req,innerCreateRequest);
                        workOrderId =  mbpWorkOrderService.createInner(innerCreateRequest);
                    }else {
                        workOrderId = mbpWorkOrderService.createAppeal(params);
                    }
                }
            } else {
                if (fieldTemplate.getBrokenHandleType() == 2) {
                    workOrderId = mbpWorkOrderService.createNewOrder(req);
                } else {
                    if (isInnerBuy(req.getImei(), spId)) {
                        MbpInnerCreateRequest innerCreateRequest = new MbpInnerCreateRequest();
                        BeanUtils.copyProperties(req,innerCreateRequest);
                        workOrderId =  mbpWorkOrderService.createInner(innerCreateRequest);
                    }else {
                        workOrderId = mbpWorkOrderService.createAppeal(params);
                    }
                }
            }
            if (workOrderId != null) {
                for (String id : req.getIds()) {
                    AppealLog appealLog = new AppealLog();
                    appealLog.setWorkorderId(workOrderId);
                    appealLog.setAlarmBrokenId(Long.parseLong(id));
                    appealLog.setAppealStatus(Constants.APPEAL_STATUS_1);
                    appealLog.setSpId(spId);
                    appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                    appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                    if (req.getBizType().equals(2)) {
                        appealLog.setAppealType(0);
                    } else if (req.getBizType().equals(3)) {
                        appealLog.setAppealType(1);
                    }
                    log.info("新增报警诉求记录：" + appealLog.toString());
                    appealLogService.save(appealLog);
                    // 更新报警/故障信息记录主表
                    if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                        LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                        historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                        HistoryAlarm historyAlarm = new HistoryAlarm();
                        historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                        historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                        historyAlarm.setAppealResult(appealLog.getAppealResult());
                        historyAlarm.setUserName(appealLog.getUserName());
                        historyAlarm.setUserAccount(appealLog.getUserAccount());
                        historyAlarm.setAppealTime(appealLog.getCreatedAt());
                        boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                        log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                    } else if (appealLog.getAppealType() == 1) {
                        LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                        historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                        HistoryBroken historyBroken = new HistoryBroken();
                        historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                        historyBroken.setAppealStatus(appealLog.getAppealStatus());
                        historyBroken.setAppealResult(appealLog.getAppealResult());
                        historyBroken.setUserName(appealLog.getUserName());
                        historyBroken.setUserAccount(appealLog.getUserAccount());
                        historyBroken.setAppealTime(appealLog.getCreatedAt());
                        boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                        log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                    }
                }
            }
        }
        sendDpMessage();
        return CommonResponse.success(null);
    }



    @ApiOperation("MBP批量处理-适用于苏州工商业大屏处理场景")
    @RequestMapping(value = "/batchProcess", method = RequestMethod.POST)
    public CommonResponse<Object> batchProcess(@RequestBody MbpBatchOrderCreateRequest req){
        log.info("MBP批量处理 req:{}",req.toString());
        String spId = ApplicationUtils.getWorkingSpId();
        //过滤 已完成的单子 req.getIds()    bizType  查表 过滤id
        List<Long> effectiveIds = new ArrayList<>();
        List<HistoryAlarmAndBrokenResponse> effectiveData = new ArrayList<>();
        if (null == req.getConsumerId() || req.getConsumerId() <= 0) return CommonResponse.failure("客户id参数必填");

        if (null != req.getBizType()){
            // 2：报警处理 3：故障处理
            if (req.getBizType() - 2 == 0 ) {
                effectiveData = historyAlarmService.getEffectiveData(req.getConsumerId());
            }
            if (req.getBizType() - 3 == 0 ) {
                effectiveData = historyBrokenService.getEffectiveData(req.getConsumerId());
            }
        }
        if (CollectionUtils.isEmpty(effectiveData)) {
            throw new BizException("未检测到报警设备");
        }
        log.info("batchAppeal.effectiveData：{}", JSON.toJSONString(effectiveData));
        if (!CollectionUtils.isEmpty(effectiveData)) effectiveIds = effectiveData.stream().map(HistoryAlarmAndBrokenResponse::getId).collect(Collectors.toList());
        log.info("batchAppeal.effectiveIds：{}",effectiveIds);
        if (CollectionUtils.isEmpty(effectiveIds)) return CommonResponse.success(null);
        //已处理
        if (req.getStatus() == 1) {
            for (Long id : effectiveIds) {
                AppealLog appealLog = new AppealLog();
                appealLog.setAlarmBrokenId(id);
                appealLog.setAppealStatus(Constants.APPEAL_STATUS_2);
                appealLog.setAppealResult(req.getAppealResult());
                appealLog.setSpId(spId);
                appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                if (req.getBizType().equals(2)) {
                    appealLog.setAppealType(0);
                } else if (req.getBizType().equals(3)) {
                    appealLog.setAppealType(1);
                }
                log.info("新增报警诉求记录："+appealLog.toString());
                appealLogService.save(appealLog);
                // 更新报警/故障信息记录主表
                if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarm = new HistoryAlarm();
                    historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                    historyAlarm.setAppealResult(appealLog.getAppealResult());
                    historyAlarm.setUserName(appealLog.getUserName());
                    historyAlarm.setUserAccount(appealLog.getUserAccount());
                    historyAlarm.setAppealTime(appealLog.getCreatedAt());
                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                } else if (appealLog.getAppealType() == 1) {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBroken = new HistoryBroken();
                    historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyBroken.setAppealStatus(appealLog.getAppealStatus());
                    historyBroken.setAppealResult(appealLog.getAppealResult());
                    historyBroken.setUserName(appealLog.getUserName());
                    historyBroken.setUserAccount(appealLog.getUserAccount());
                    historyBroken.setAppealTime(appealLog.getCreatedAt());
                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                }
            }
        } else if (req.getStatus() == 2) {
            //转工单
            Long workOrderId;

            QueryWrapper<FieldTemplate> templateQueryWrapper = new QueryWrapper<>();
            templateQueryWrapper.lambda().eq(FieldTemplate::getSpId, spId)
                    .eq(FieldTemplate::getTemplateType, 1)
                    .eq(FieldTemplate::getIsDeleted, 0);
            FieldTemplate fieldTemplate = fieldTemplateService.getOne(templateQueryWrapper);
            req.setImei(effectiveData.get(0).getIMEI());

            List<String> imeiList = effectiveData.stream().map(HistoryAlarmAndBrokenResponse::getDeviceId).collect(Collectors.toList());
            List<Dtu> dtuList = equipmentService.queryDeviceByImei(imeiList, spId);
            if (!CollectionUtils.isEmpty(dtuList)) {
                Integer source = dtuList.get(0).getSource();
                for (Dtu dtu : dtuList) {
                    if (source != dtu.getSource()) {
                        throw new BizException("该客户下设备来源不同，不能批量处理");
                    }
                }
            }
            req.setEffectiveData(effectiveData);
            if (req.getBizType() == 2) {
                if (fieldTemplate.getAlarmHandleType() == 2) {
                    workOrderId = mbpWorkOrderService.createNewOrderBatch(req);
                } else {
                    if (isInnerBuy(effectiveData.get(0).getIMEI(), spId)) {
                        workOrderId =  mbpWorkOrderService.createInnerBatch(req);
                    }else {
                        workOrderId = mbpWorkOrderService.createBatch(req);
                    }
                }
            } else {
                if (fieldTemplate.getBrokenHandleType() == 2) {
                    workOrderId = mbpWorkOrderService.createNewOrderBatch(req);
                } else {
                    if (isInnerBuy(effectiveData.get(0).getIMEI(), spId)) {
                        workOrderId =  mbpWorkOrderService.createInnerBatch(req);
                    }else {
                        workOrderId = mbpWorkOrderService.createBatch(req);
                    }
                }
            }
            for (HistoryAlarmAndBrokenResponse entity :effectiveData) {
                if (workOrderId != null) {
                    AppealLog appealLog = new AppealLog();
                    appealLog.setWorkorderId(workOrderId);
                    appealLog.setAlarmBrokenId(entity.getId());
                    appealLog.setAppealStatus(Constants.APPEAL_STATUS_1);
                    appealLog.setSpId(spId);
                    appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                    appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                    if (req.getBizType().equals(2)) {
                        appealLog.setAppealType(0);
                    } else if (req.getBizType().equals(3)) {
                        appealLog.setAppealType(1);
                    }
                    log.info("新增报警诉求记录：" + appealLog.toString());
                    appealLogService.save(appealLog);
                    // 更新报警/故障信息记录主表
                    if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                        LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                        historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                        HistoryAlarm historyAlarm = new HistoryAlarm();
                        historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                        historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                        historyAlarm.setAppealResult(appealLog.getAppealResult());
                        historyAlarm.setUserName(appealLog.getUserName());
                        historyAlarm.setUserAccount(appealLog.getUserAccount());
                        historyAlarm.setAppealTime(appealLog.getCreatedAt());
                        boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                        log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                    } else if (appealLog.getAppealType() == 1) {
                        LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                        historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                        HistoryBroken historyBroken = new HistoryBroken();
                        historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                        historyBroken.setAppealStatus(appealLog.getAppealStatus());
                        historyBroken.setAppealResult(appealLog.getAppealResult());
                        historyBroken.setUserName(appealLog.getUserName());
                        historyBroken.setUserAccount(appealLog.getUserAccount());
                        historyBroken.setAppealTime(appealLog.getCreatedAt());
                        boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                        log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                    }
                }
            }
        }
        sendDpMessage();
        return CommonResponse.success(null);
    }

    @ApiOperation(value = "诉求历史列表-客户管理-模板一")
    @PostMapping("/workOrderHistory")
    public CommonResponse<PageUtil<AppealHistoryResponse>> workOrderHistory(@RequestBody @Valid AppealHistoryRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());
        if (BIND_CHANNEL_GAS !=request.getTemplateType()){
            throw new BizException("只允许模板一调用本接口");
        }
        return CommonResponse.success(mbpWorkOrderService.appealHistory(request));
    }


    @ApiOperation(value = "更新诉求状态-客户管理-模板一")
    @PostMapping("/appealHistory/updateStatus")
    public CommonResponse<Object> updateAppealStatus(@RequestBody @Valid AppealHistoryRequest request) {
        request.setTemplateType(headerUtil.getTemplateType());
        if (BIND_CHANNEL_GAS !=request.getTemplateType()){
            throw new BizException("只允许模板一调用本接口");
        }
        mbpWorkOrderService.updateAppealStatus(request);
        return CommonResponse.success("success");
    }


    @ApiOperation(value = "诉求处理部门查询")
    @PostMapping("/org/orgInfos")
    public CommonResponse<Object> orgInfos(@RequestBody @Valid OrgInfosRequest request) {
        return CommonResponse.success( mbpWorkOrderService.orgInfos(request));
    }

    private boolean isInnerBuy(String imei, String spId) {
        Dtu one = equipmentService.getDeviceByImei(imei, spId);
        log.info("isInnerBuy-one:{},{}",one,spId );
        if (one != null && one.getSource() == 1){
            return true;
        }
        return false;
    }

    private void sendDpMessage(){
        try {
            String spId = ApplicationUtils.getWorkingSpId();
            Map<String, String> params = new HashMap<>();
            params.put("source", "orderHandleFlag");
            webSocketDpProcess.redisTopicSendMsg(spId, JSONUtil.toJsonStr(params));
        }catch(Exception e){
            log.error("发送大屏消息",e);
        }
    }

}

